acda5d655a27c451a81adad5d7a6c2e73a94a2d6
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /**
2 * Base library for MediaWiki.
3 *
4 * @class mw
5 * @alternateClassName mediaWiki
6 * @singleton
7 */
8
9 var mw = ( function ( $, undefined ) {
10 'use strict';
11
12 /* Private Members */
13
14 var hasOwn = Object.prototype.hasOwnProperty,
15 slice = Array.prototype.slice;
16
17 /**
18 * Log a message to window.console, if possible. Useful to force logging of some
19 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
20 * Gets console references in each invocation, so that delayed debugging tools work
21 * fine. No need for optimization here, which would only result in losing logs.
22 *
23 * @private
24 * @param {string} msg text for the log entry.
25 * @param {Error} [e]
26 */
27 function log( msg, e ) {
28 var console = window.console;
29 if ( console && console.log ) {
30 console.log( msg );
31 // If we have an exception object, log it through .error() to trigger
32 // proper stacktraces in browsers that support it. There are no (known)
33 // browsers that don't support .error(), that do support .log() and
34 // have useful exception handling through .log().
35 if ( e && console.error ) {
36 console.error( String( e ), e );
37 }
38 }
39 }
40
41 /* Object constructors */
42
43 /**
44 * Creates an object that can be read from or written to from prototype functions
45 * that allow both single and multiple variables at once.
46 *
47 * @example
48 *
49 * var addies, wanted, results;
50 *
51 * // Create your address book
52 * addies = new mw.Map();
53 *
54 * // This data could be coming from an external source (eg. API/AJAX)
55 * addies.set( {
56 * 'John Doe' : '10 Wall Street, New York, USA',
57 * 'Jane Jackson' : '21 Oxford St, London, UK',
58 * 'Dominique van Halen' : 'Kalverstraat 7, Amsterdam, NL'
59 * } );
60 *
61 * wanted = ['Dominique van Halen', 'George Johnson', 'Jane Jackson'];
62 *
63 * // You can detect missing keys first
64 * if ( !addies.exists( wanted ) ) {
65 * // One or more are missing (in this case: "George Johnson")
66 * mw.log( 'One or more names were not found in your address book' );
67 * }
68 *
69 * // Or just let it give you what it can
70 * results = addies.get( wanted, 'Middle of Nowhere, Alaska, US' );
71 * mw.log( results['Jane Jackson'] ); // "21 Oxford St, London, UK"
72 * mw.log( results['George Johnson'] ); // "Middle of Nowhere, Alaska, US"
73 *
74 * @class mw.Map
75 *
76 * @constructor
77 * @param {boolean} [global=false] Whether to store the values in the global window
78 * object or a exclusively in the object property 'values'.
79 */
80 function Map( global ) {
81 this.values = global === true ? window : {};
82 return this;
83 }
84
85 Map.prototype = {
86 /**
87 * Get the value of one or multiple a keys.
88 *
89 * If called with no arguments, all values will be returned.
90 *
91 * @param {string|Array} selection String key or array of keys to get values for.
92 * @param {Mixed} [fallback] Value to use in case key(s) do not exist.
93 * @return mixed If selection was a string returns the value or null,
94 * If selection was an array, returns an object of key/values (value is null if not found),
95 * If selection was not passed or invalid, will return the 'values' object member (be careful as
96 * objects are always passed by reference in JavaScript!).
97 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
98 */
99 get: function ( selection, fallback ) {
100 var results, i;
101 // If we only do this in the `return` block, it'll fail for the
102 // call to get() from the mutli-selection block.
103 fallback = arguments.length > 1 ? fallback : null;
104
105 if ( $.isArray( selection ) ) {
106 selection = slice.call( selection );
107 results = {};
108 for ( i = 0; i < selection.length; i++ ) {
109 results[selection[i]] = this.get( selection[i], fallback );
110 }
111 return results;
112 }
113
114 if ( typeof selection === 'string' ) {
115 if ( !hasOwn.call( this.values, selection ) ) {
116 return fallback;
117 }
118 return this.values[selection];
119 }
120
121 if ( selection === undefined ) {
122 return this.values;
123 }
124
125 // invalid selection key
126 return null;
127 },
128
129 /**
130 * Sets one or multiple key/value pairs.
131 *
132 * @param {string|Object} selection String key to set value for, or object mapping keys to values.
133 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
134 * @return {Boolean} This returns true on success, false on failure.
135 */
136 set: function ( selection, value ) {
137 var s;
138
139 if ( $.isPlainObject( selection ) ) {
140 for ( s in selection ) {
141 this.values[s] = selection[s];
142 }
143 return true;
144 }
145 if ( typeof selection === 'string' && arguments.length > 1 ) {
146 this.values[selection] = value;
147 return true;
148 }
149 return false;
150 },
151
152 /**
153 * Checks if one or multiple keys exist.
154 *
155 * @param {Mixed} selection String key or array of keys to check
156 * @return {boolean} Existence of key(s)
157 */
158 exists: function ( selection ) {
159 var s;
160
161 if ( $.isArray( selection ) ) {
162 for ( s = 0; s < selection.length; s++ ) {
163 if ( typeof selection[s] !== 'string' || !hasOwn.call( this.values, selection[s] ) ) {
164 return false;
165 }
166 }
167 return true;
168 }
169 return typeof selection === 'string' && hasOwn.call( this.values, selection );
170 }
171 };
172
173 /**
174 * Object constructor for messages.
175 *
176 * Similar to the Message class in MediaWiki PHP.
177 *
178 * Format defaults to 'text'.
179 *
180 * @class mw.Message
181 *
182 * @constructor
183 * @param {mw.Map} map Message storage
184 * @param {string} key
185 * @param {Array} [parameters]
186 */
187 function Message( map, key, parameters ) {
188 this.format = 'text';
189 this.map = map;
190 this.key = key;
191 this.parameters = parameters === undefined ? [] : slice.call( parameters );
192 return this;
193 }
194
195 Message.prototype = {
196 /**
197 * Simple message parser, does $N replacement and nothing else.
198 *
199 * This may be overridden to provide a more complex message parser.
200 *
201 * The primary override is in mediawiki.jqueryMsg.
202 *
203 * This function will not be called for nonexistent messages.
204 */
205 parser: function () {
206 var parameters = this.parameters;
207 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
208 var index = parseInt( match, 10 ) - 1;
209 return parameters[index] !== undefined ? parameters[index] : '$' + match;
210 } );
211 },
212
213 /**
214 * Appends (does not replace) parameters for replacement to the .parameters property.
215 *
216 * @param {Array} parameters
217 * @chainable
218 */
219 params: function ( parameters ) {
220 var i;
221 for ( i = 0; i < parameters.length; i += 1 ) {
222 this.parameters.push( parameters[i] );
223 }
224 return this;
225 },
226
227 /**
228 * Converts message object to its string form based on the state of format.
229 *
230 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
231 */
232 toString: function () {
233 var text;
234
235 if ( !this.exists() ) {
236 // Use <key> as text if key does not exist
237 if ( this.format === 'escaped' || this.format === 'parse' ) {
238 // format 'escaped' and 'parse' need to have the brackets and key html escaped
239 return mw.html.escape( '<' + this.key + '>' );
240 }
241 return '<' + this.key + '>';
242 }
243
244 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
245 text = this.parser();
246 }
247
248 if ( this.format === 'escaped' ) {
249 text = this.parser();
250 text = mw.html.escape( text );
251 }
252
253 return text;
254 },
255
256 /**
257 * Changes format to 'parse' and converts message to string
258 *
259 * If jqueryMsg is loaded, this parses the message text from wikitext
260 * (where supported) to HTML
261 *
262 * Otherwise, it is equivalent to plain.
263 *
264 * @return {string} String form of parsed message
265 */
266 parse: function () {
267 this.format = 'parse';
268 return this.toString();
269 },
270
271 /**
272 * Changes format to 'plain' and converts message to string
273 *
274 * This substitutes parameters, but otherwise does not change the
275 * message text.
276 *
277 * @return {string} String form of plain message
278 */
279 plain: function () {
280 this.format = 'plain';
281 return this.toString();
282 },
283
284 /**
285 * Changes format to 'text' and converts message to string
286 *
287 * If jqueryMsg is loaded, {{-transformation is done where supported
288 * (such as {{plural:}}, {{gender:}}, {{int:}}).
289 *
290 * Otherwise, it is equivalent to plain.
291 */
292 text: function () {
293 this.format = 'text';
294 return this.toString();
295 },
296
297 /**
298 * Changes the format to 'escaped' and converts message to string
299 *
300 * This is equivalent to using the 'text' format (see text method), then
301 * HTML-escaping the output.
302 *
303 * @return {string} String form of html escaped message
304 */
305 escaped: function () {
306 this.format = 'escaped';
307 return this.toString();
308 },
309
310 /**
311 * Checks if message exists
312 *
313 * @see mw.Map#exists
314 * @return {boolean}
315 */
316 exists: function () {
317 return this.map.exists( this.key );
318 }
319 };
320
321 return {
322 /* Public Members */
323
324 /**
325 * Dummy placeholder for {@link mw.log}
326 * @method
327 */
328 log: ( function () {
329 var log = function () {};
330 log.warn = function () {};
331 log.deprecate = function ( obj, key, val ) {
332 obj[key] = val;
333 };
334 return log;
335 }() ),
336
337 // Make the Map constructor publicly available.
338 Map: Map,
339
340 // Make the Message constructor publicly available.
341 Message: Message,
342
343 /**
344 * Map of configuration values
345 *
346 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
347 * on MediaWiki.org.
348 *
349 * If `$wgLegacyJavaScriptGlobals` is true, this Map will put its values in the
350 * global window object.
351 *
352 * @property {mw.Map} config
353 */
354 // Dummy placeholder. Re-assigned in ResourceLoaderStartupModule with an instance of `mw.Map`.
355 config: null,
356
357 /**
358 * Empty object that plugins can be installed in.
359 * @property
360 */
361 libs: {},
362
363 /**
364 * Access container for deprecated functionality that can be moved from
365 * from their legacy location and attached to this object (e.g. a global
366 * function that is deprecated and as stop-gap can be exposed through here).
367 *
368 * This was reserved for future use but never ended up being used.
369 *
370 * @deprecated since 1.22: Let deprecated identifiers keep their original name
371 * and use mw.log#deprecate to create an access container for tracking.
372 * @property
373 */
374 legacy: {},
375
376 /**
377 * Localization system
378 * @property {mw.Map}
379 */
380 messages: new Map(),
381
382 /* Public Methods */
383
384 /**
385 * Get a message object.
386 *
387 * Similar to wfMessage() in MediaWiki PHP.
388 *
389 * @param {string} key Key of message to get
390 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
391 * @return {mw.Message}
392 */
393 message: function ( key ) {
394 // Variadic arguments
395 var parameters = slice.call( arguments, 1 );
396 return new Message( mw.messages, key, parameters );
397 },
398
399 /**
400 * Get a message string using 'text' format.
401 *
402 * Similar to wfMsg() in MediaWiki PHP.
403 *
404 * @see mw.Message
405 * @param {string} key Key of message to get
406 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
407 * @return {string}
408 */
409 msg: function () {
410 return mw.message.apply( mw.message, arguments ).toString();
411 },
412
413 /**
414 * Client-side module loader which integrates with the MediaWiki ResourceLoader
415 * @class mw.loader
416 * @singleton
417 */
418 loader: ( function () {
419
420 /* Private Members */
421
422 /**
423 * Mapping of registered modules
424 *
425 * The jquery module is pre-registered, because it must have already
426 * been provided for this object to have been built, and in debug mode
427 * jquery would have been provided through a unique loader request,
428 * making it impossible to hold back registration of jquery until after
429 * mediawiki.
430 *
431 * For exact details on support for script, style and messages, look at
432 * mw.loader.implement.
433 *
434 * Format:
435 * {
436 * 'moduleName': {
437 * 'version': ############## (unix timestamp),
438 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
439 * 'group': 'somegroup', (or) null,
440 * 'source': 'local', 'someforeignwiki', (or) null
441 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error' or 'missing'
442 * 'script': ...,
443 * 'style': ...,
444 * 'messages': { 'key': 'value' },
445 * }
446 * }
447 *
448 * @property
449 * @private
450 */
451 var registry = {},
452 //
453 // Mapping of sources, keyed by source-id, values are objects.
454 // Format:
455 // {
456 // 'sourceId': {
457 // 'loadScript': 'http://foo.bar/w/load.php'
458 // }
459 // }
460 //
461 sources = {},
462 // List of modules which will be loaded as when ready
463 batch = [],
464 // List of modules to be loaded
465 queue = [],
466 // List of callback functions waiting for modules to be ready to be called
467 jobs = [],
468 // Selector cache for the marker element. Use getMarker() to get/use the marker!
469 $marker = null,
470 // Buffer for addEmbeddedCSS.
471 cssBuffer = '',
472 // Callbacks for addEmbeddedCSS.
473 cssCallbacks = $.Callbacks();
474
475 /* Private methods */
476
477 function getMarker() {
478 // Cached ?
479 if ( $marker ) {
480 return $marker;
481 }
482
483 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
484 if ( $marker.length ) {
485 return $marker;
486 }
487 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
488 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
489
490 return $marker;
491 }
492
493 /**
494 * Create a new style tag and add it to the DOM.
495 *
496 * @private
497 * @param {string} text CSS text
498 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag should be
499 * inserted before. Otherwise it will be appended to `<head>`.
500 * @return {HTMLElement} Reference to the created `<style>` element.
501 */
502 function newStyleTag( text, nextnode ) {
503 var s = document.createElement( 'style' );
504 // Insert into document before setting cssText (bug 33305)
505 if ( nextnode ) {
506 // Must be inserted with native insertBefore, not $.fn.before.
507 // When using jQuery to insert it, like $nextnode.before( s ),
508 // then IE6 will throw "Access is denied" when trying to append
509 // to .cssText later. Some kind of weird security measure.
510 // http://stackoverflow.com/q/12586482/319266
511 // Works: jsfiddle.net/zJzMy/1
512 // Fails: jsfiddle.net/uJTQz
513 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
514 if ( nextnode.jquery ) {
515 nextnode = nextnode.get( 0 );
516 }
517 nextnode.parentNode.insertBefore( s, nextnode );
518 } else {
519 document.getElementsByTagName( 'head' )[0].appendChild( s );
520 }
521 if ( s.styleSheet ) {
522 // IE
523 s.styleSheet.cssText = text;
524 } else {
525 // Other browsers.
526 // (Safari sometimes borks on non-string values,
527 // play safe by casting to a string, just in case.)
528 s.appendChild( document.createTextNode( String( text ) ) );
529 }
530 return s;
531 }
532
533 /**
534 * Checks whether it is safe to add this css to a stylesheet.
535 *
536 * @private
537 * @param {string} cssText
538 * @return {boolean} False if a new one must be created.
539 */
540 function canExpandStylesheetWith( cssText ) {
541 // Makes sure that cssText containing `@import`
542 // rules will end up in a new stylesheet (as those only work when
543 // placed at the start of a stylesheet; bug 35562).
544 return cssText.indexOf( '@import' ) === -1;
545 }
546
547 /**
548 * Add a bit of CSS text to the current browser page.
549 *
550 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
551 * or create a new one based on whether the given `cssText` is safe for extension.
552 *
553 * @param {string} [cssText=cssBuffer] If called without cssText,
554 * the internal buffer will be inserted instead.
555 * @param {Function} [callback]
556 */
557 function addEmbeddedCSS( cssText, callback ) {
558 var $style, styleEl;
559
560 if ( callback ) {
561 cssCallbacks.add( callback );
562 }
563
564 // Yield once before inserting the <style> tag. There are likely
565 // more calls coming up which we can combine this way.
566 // Appending a stylesheet and waiting for the browser to repaint
567 // is fairly expensive, this reduces it (bug 45810)
568 if ( cssText ) {
569 // Be careful not to extend the buffer with css that needs a new stylesheet
570 if ( !cssBuffer || canExpandStylesheetWith( cssText ) ) {
571 // Linebreak for somewhat distinguishable sections
572 // (the rl-cachekey comment separating each)
573 cssBuffer += '\n' + cssText;
574 // TODO: Use requestAnimationFrame in the future which will
575 // perform even better by not injecting styles while the browser
576 // is paiting.
577 setTimeout( function () {
578 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
579 // (below version 13) has the non-standard behaviour of passing a
580 // numerical "lateness" value as first argument to this callback
581 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
582 addEmbeddedCSS();
583 } );
584 return;
585 }
586
587 // This is a delayed call and we got a buffer still
588 } else if ( cssBuffer ) {
589 cssText = cssBuffer;
590 cssBuffer = '';
591 } else {
592 // This is a delayed call, but buffer is already cleared by
593 // another delayed call.
594 return;
595 }
596
597 // By default, always create a new <style>. Appending text
598 // to a <style> tag means the contents have to be re-parsed (bug 45810).
599 // Except, of course, in IE below 9, in there we default to
600 // re-using and appending to a <style> tag due to the
601 // IE stylesheet limit (bug 31676).
602 if ( 'documentMode' in document && document.documentMode <= 9 ) {
603
604 $style = getMarker().prev();
605 // Verify that the the element before Marker actually is a
606 // <style> tag and one that came from ResourceLoader
607 // (not some other style tag or even a `<meta>` or `<script>`).
608 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
609 // There's already a dynamic <style> tag present and
610 // canExpandStylesheetWith() gave a green light to append more to it.
611 styleEl = $style.get( 0 );
612 if ( styleEl.styleSheet ) {
613 try {
614 styleEl.styleSheet.cssText += cssText; // IE
615 } catch ( e ) {
616 log( 'addEmbeddedCSS fail', e );
617 }
618 } else {
619 styleEl.appendChild( document.createTextNode( String( cssText ) ) );
620 }
621 cssCallbacks.fire().empty();
622 return;
623 }
624 }
625
626 $( newStyleTag( cssText, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
627
628 cssCallbacks.fire().empty();
629 }
630
631 /**
632 * Generates an ISO8601 "basic" string from a UNIX timestamp
633 * @private
634 */
635 function formatVersionNumber( timestamp ) {
636 var d = new Date();
637 function pad( a, b, c ) {
638 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
639 }
640 d.setTime( timestamp * 1000 );
641 return [
642 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
643 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
644 ].join( '' );
645 }
646
647 /**
648 * Resolves dependencies and detects circular references.
649 *
650 * @private
651 * @param {string} module Name of the top-level module whose dependencies shall be
652 * resolved and sorted.
653 * @param {Array} resolved Returns a topological sort of the given module and its
654 * dependencies, such that later modules depend on earlier modules. The array
655 * contains the module names. If the array contains already some module names,
656 * this function appends its result to the pre-existing array.
657 * @param {Object} [unresolved] Hash used to track the current dependency
658 * chain; used to report loops in the dependency graph.
659 * @throws {Error} If any unregistered module or a dependency loop is encountered
660 */
661 function sortDependencies( module, resolved, unresolved ) {
662 var n, deps, len;
663
664 if ( registry[module] === undefined ) {
665 throw new Error( 'Unknown dependency: ' + module );
666 }
667 // Resolves dynamic loader function and replaces it with its own results
668 if ( $.isFunction( registry[module].dependencies ) ) {
669 registry[module].dependencies = registry[module].dependencies();
670 // Ensures the module's dependencies are always in an array
671 if ( typeof registry[module].dependencies !== 'object' ) {
672 registry[module].dependencies = [registry[module].dependencies];
673 }
674 }
675 if ( $.inArray( module, resolved ) !== -1 ) {
676 // Module already resolved; nothing to do.
677 return;
678 }
679 // unresolved is optional, supply it if not passed in
680 if ( !unresolved ) {
681 unresolved = {};
682 }
683 // Tracks down dependencies
684 deps = registry[module].dependencies;
685 len = deps.length;
686 for ( n = 0; n < len; n += 1 ) {
687 if ( $.inArray( deps[n], resolved ) === -1 ) {
688 if ( unresolved[deps[n]] ) {
689 throw new Error(
690 'Circular reference detected: ' + module +
691 ' -> ' + deps[n]
692 );
693 }
694
695 // Add to unresolved
696 unresolved[module] = true;
697 sortDependencies( deps[n], resolved, unresolved );
698 delete unresolved[module];
699 }
700 }
701 resolved[resolved.length] = module;
702 }
703
704 /**
705 * Gets a list of module names that a module depends on in their proper dependency
706 * order.
707 *
708 * @private
709 * @param {string} module Module name or array of string module names
710 * @return {Array} list of dependencies, including 'module'.
711 * @throws {Error} If circular reference is detected
712 */
713 function resolve( module ) {
714 var m, resolved;
715
716 // Allow calling with an array of module names
717 if ( $.isArray( module ) ) {
718 resolved = [];
719 for ( m = 0; m < module.length; m += 1 ) {
720 sortDependencies( module[m], resolved );
721 }
722 return resolved;
723 }
724
725 if ( typeof module === 'string' ) {
726 resolved = [];
727 sortDependencies( module, resolved );
728 return resolved;
729 }
730
731 throw new Error( 'Invalid module argument: ' + module );
732 }
733
734 /**
735 * Narrows a list of module names down to those matching a specific
736 * state (see comment on top of this scope for a list of valid states).
737 * One can also filter for 'unregistered', which will return the
738 * modules names that don't have a registry entry.
739 *
740 * @private
741 * @param {string|string[]} states Module states to filter by
742 * @param {Array} [modules] List of module names to filter (optional, by default the entire
743 * registry is used)
744 * @return {Array} List of filtered module names
745 */
746 function filter( states, modules ) {
747 var list, module, s, m;
748
749 // Allow states to be given as a string
750 if ( typeof states === 'string' ) {
751 states = [states];
752 }
753 // If called without a list of modules, build and use a list of all modules
754 list = [];
755 if ( modules === undefined ) {
756 modules = [];
757 for ( module in registry ) {
758 modules[modules.length] = module;
759 }
760 }
761 // Build a list of modules which are in one of the specified states
762 for ( s = 0; s < states.length; s += 1 ) {
763 for ( m = 0; m < modules.length; m += 1 ) {
764 if ( registry[modules[m]] === undefined ) {
765 // Module does not exist
766 if ( states[s] === 'unregistered' ) {
767 // OK, undefined
768 list[list.length] = modules[m];
769 }
770 } else {
771 // Module exists, check state
772 if ( registry[modules[m]].state === states[s] ) {
773 // OK, correct state
774 list[list.length] = modules[m];
775 }
776 }
777 }
778 }
779 return list;
780 }
781
782 /**
783 * Determine whether all dependencies are in state 'ready', which means we may
784 * execute the module or job now.
785 *
786 * @private
787 * @param {Array} dependencies Dependencies (module names) to be checked.
788 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
789 */
790 function allReady( dependencies ) {
791 return filter( 'ready', dependencies ).length === dependencies.length;
792 }
793
794 /**
795 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
796 * and modules that depend upon this module. if the given module failed, propagate the 'error'
797 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
798 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
799 *
800 * @private
801 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
802 */
803 function handlePending( module ) {
804 var j, job, hasErrors, m, stateChange;
805
806 // Modules.
807 if ( $.inArray( registry[module].state, ['error', 'missing'] ) !== -1 ) {
808 // If the current module failed, mark all dependent modules also as failed.
809 // Iterate until steady-state to propagate the error state upwards in the
810 // dependency tree.
811 do {
812 stateChange = false;
813 for ( m in registry ) {
814 if ( $.inArray( registry[m].state, ['error', 'missing'] ) === -1 ) {
815 if ( filter( ['error', 'missing'], registry[m].dependencies ).length > 0 ) {
816 registry[m].state = 'error';
817 stateChange = true;
818 }
819 }
820 }
821 } while ( stateChange );
822 }
823
824 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
825 for ( j = 0; j < jobs.length; j += 1 ) {
826 hasErrors = filter( ['error', 'missing'], jobs[j].dependencies ).length > 0;
827 if ( hasErrors || allReady( jobs[j].dependencies ) ) {
828 // All dependencies satisfied, or some have errors
829 job = jobs[j];
830 jobs.splice( j, 1 );
831 j -= 1;
832 try {
833 if ( hasErrors ) {
834 if ( $.isFunction( job.error ) ) {
835 job.error( new Error( 'Module ' + module + ' has failed dependencies' ), [module] );
836 }
837 } else {
838 if ( $.isFunction( job.ready ) ) {
839 job.ready();
840 }
841 }
842 } catch ( e ) {
843 // A user-defined callback raised an exception.
844 // Swallow it to protect our state machine!
845 log( 'Exception thrown by job.error', e );
846 }
847 }
848 }
849
850 if ( registry[module].state === 'ready' ) {
851 // The current module became 'ready'. Set it in the module store, and recursively execute all
852 // dependent modules that are loaded and now have all dependencies satisfied.
853 mw.loader.store.set( module, registry[module] );
854 for ( m in registry ) {
855 if ( registry[m].state === 'loaded' && allReady( registry[m].dependencies ) ) {
856 execute( m );
857 }
858 }
859 }
860 }
861
862 /**
863 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
864 * depending on whether document-ready has occurred yet and whether we are in async mode.
865 *
866 * @private
867 * @param {string} src URL to script, will be used as the src attribute in the script tag
868 * @param {Function} [callback] Callback which will be run when the script is done
869 */
870 function addScript( src, callback, async ) {
871 /*jshint evil:true */
872 var script, head, done;
873
874 // Using isReady directly instead of storing it locally from
875 // a $.fn.ready callback (bug 31895).
876 if ( $.isReady || async ) {
877 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
878 // it uses XHR and eval for same-domain scripts, which we don't want because it
879 // messes up line numbers.
880 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
881
882 // IE-safe way of getting the <head>. document.head isn't supported
883 // in old IE, and doesn't work when in the <head>.
884 done = false;
885 head = document.getElementsByTagName( 'head' )[0] || document.body;
886
887 script = document.createElement( 'script' );
888 script.async = true;
889 script.src = src;
890 if ( $.isFunction( callback ) ) {
891 script.onload = script.onreadystatechange = function () {
892 if (
893 !done
894 && (
895 !script.readyState
896 || /loaded|complete/.test( script.readyState )
897 )
898 ) {
899 done = true;
900
901 // Handle memory leak in IE
902 script.onload = script.onreadystatechange = null;
903
904 // Detach the element from the document
905 if ( script.parentNode ) {
906 script.parentNode.removeChild( script );
907 }
908
909 // Dereference the element from javascript
910 script = undefined;
911
912 callback();
913 }
914 };
915 }
916
917 if ( window.opera ) {
918 // Appending to the <head> blocks rendering completely in Opera,
919 // so append to the <body> after document ready. This means the
920 // scripts only start loading after the document has been rendered,
921 // but so be it. Opera users don't deserve faster web pages if their
922 // browser makes it impossible.
923 $( function () {
924 document.body.appendChild( script );
925 } );
926 } else {
927 head.appendChild( script );
928 }
929 } else {
930 document.write( mw.html.element( 'script', { 'src': src }, '' ) );
931 if ( $.isFunction( callback ) ) {
932 // Document.write is synchronous, so this is called when it's done
933 // FIXME: that's a lie. doc.write isn't actually synchronous
934 callback();
935 }
936 }
937 }
938
939 /**
940 * Executes a loaded module, making it ready to use
941 *
942 * @private
943 * @param {string} module Module name to execute
944 */
945 function execute( module ) {
946 var key, value, media, i, urls, cssHandle, checkCssHandles,
947 cssHandlesRegistered = false;
948
949 if ( registry[module] === undefined ) {
950 throw new Error( 'Module has not been registered yet: ' + module );
951 } else if ( registry[module].state === 'registered' ) {
952 throw new Error( 'Module has not been requested from the server yet: ' + module );
953 } else if ( registry[module].state === 'loading' ) {
954 throw new Error( 'Module has not completed loading yet: ' + module );
955 } else if ( registry[module].state === 'ready' ) {
956 throw new Error( 'Module has already been executed: ' + module );
957 }
958
959 /**
960 * Define loop-function here for efficiency
961 * and to avoid re-using badly scoped variables.
962 * @ignore
963 */
964 function addLink( media, url ) {
965 var el = document.createElement( 'link' );
966 getMarker().before( el ); // IE: Insert in dom before setting href
967 el.rel = 'stylesheet';
968 if ( media && media !== 'all' ) {
969 el.media = media;
970 }
971 el.href = url;
972 }
973
974 function runScript() {
975 var script, markModuleReady, nestedAddScript;
976 try {
977 script = registry[module].script;
978 markModuleReady = function () {
979 registry[module].state = 'ready';
980 handlePending( module );
981 };
982 nestedAddScript = function ( arr, callback, async, i ) {
983 // Recursively call addScript() in its own callback
984 // for each element of arr.
985 if ( i >= arr.length ) {
986 // We're at the end of the array
987 callback();
988 return;
989 }
990
991 addScript( arr[i], function () {
992 nestedAddScript( arr, callback, async, i + 1 );
993 }, async );
994 };
995
996 if ( $.isArray( script ) ) {
997 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
998 } else if ( $.isFunction( script ) ) {
999 registry[module].state = 'ready';
1000 script( $ );
1001 handlePending( module );
1002 }
1003 } catch ( e ) {
1004 // This needs to NOT use mw.log because these errors are common in production mode
1005 // and not in debug mode, such as when a symbol that should be global isn't exported
1006 log( 'Exception thrown by ' + module, e );
1007 registry[module].state = 'error';
1008 handlePending( module );
1009 }
1010 }
1011
1012 // This used to be inside runScript, but since that is now fired asychronously
1013 // (after CSS is loaded) we need to set it here right away. It is crucial that
1014 // when execute() is called this is set synchronously, otherwise modules will get
1015 // executed multiple times as the registry will state that it isn't loading yet.
1016 registry[module].state = 'loading';
1017
1018 // Add localizations to message system
1019 if ( $.isPlainObject( registry[module].messages ) ) {
1020 mw.messages.set( registry[module].messages );
1021 }
1022
1023 if ( $.isReady || registry[module].async ) {
1024 // Make sure we don't run the scripts until all (potentially asynchronous)
1025 // stylesheet insertions have completed.
1026 ( function () {
1027 var pending = 0;
1028 checkCssHandles = function () {
1029 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1030 // one of the cssHandles is fired while we're still creating more handles.
1031 if ( cssHandlesRegistered && pending === 0 && runScript ) {
1032 runScript();
1033 runScript = undefined; // Revoke
1034 }
1035 };
1036 cssHandle = function () {
1037 var check = checkCssHandles;
1038 pending++;
1039 return function () {
1040 if (check) {
1041 pending--;
1042 check();
1043 check = undefined; // Revoke
1044 }
1045 };
1046 };
1047 }() );
1048 } else {
1049 // We are in blocking mode, and so we can't afford to wait for CSS
1050 cssHandle = function () {};
1051 // Run immediately
1052 checkCssHandles = runScript;
1053 }
1054
1055 // Process styles (see also mw.loader.implement)
1056 // * back-compat: { <media>: css }
1057 // * back-compat: { <media>: [url, ..] }
1058 // * { "css": [css, ..] }
1059 // * { "url": { <media>: [url, ..] } }
1060 if ( $.isPlainObject( registry[module].style ) ) {
1061 for ( key in registry[module].style ) {
1062 value = registry[module].style[key];
1063 media = undefined;
1064
1065 if ( key !== 'url' && key !== 'css' ) {
1066 // Backwards compatibility, key is a media-type
1067 if ( typeof value === 'string' ) {
1068 // back-compat: { <media>: css }
1069 // Ignore 'media' because it isn't supported (nor was it used).
1070 // Strings are pre-wrapped in "@media". The media-type was just ""
1071 // (because it had to be set to something).
1072 // This is one of the reasons why this format is no longer used.
1073 addEmbeddedCSS( value, cssHandle() );
1074 } else {
1075 // back-compat: { <media>: [url, ..] }
1076 media = key;
1077 key = 'bc-url';
1078 }
1079 }
1080
1081 // Array of css strings in key 'css',
1082 // or back-compat array of urls from media-type
1083 if ( $.isArray( value ) ) {
1084 for ( i = 0; i < value.length; i += 1 ) {
1085 if ( key === 'bc-url' ) {
1086 // back-compat: { <media>: [url, ..] }
1087 addLink( media, value[i] );
1088 } else if ( key === 'css' ) {
1089 // { "css": [css, ..] }
1090 addEmbeddedCSS( value[i], cssHandle() );
1091 }
1092 }
1093 // Not an array, but a regular object
1094 // Array of urls inside media-type key
1095 } else if ( typeof value === 'object' ) {
1096 // { "url": { <media>: [url, ..] } }
1097 for ( media in value ) {
1098 urls = value[media];
1099 for ( i = 0; i < urls.length; i += 1 ) {
1100 addLink( media, urls[i] );
1101 }
1102 }
1103 }
1104 }
1105 }
1106
1107 // Kick off.
1108 cssHandlesRegistered = true;
1109 checkCssHandles();
1110 }
1111
1112 /**
1113 * Adds a dependencies to the queue with optional callbacks to be run
1114 * when the dependencies are ready or fail
1115 *
1116 * @private
1117 * @param {string|string[]} dependencies Module name or array of string module names
1118 * @param {Function} [ready] Callback to execute when all dependencies are ready
1119 * @param {Function} [error] Callback to execute when any dependency fails
1120 * @param {boolean} [async] If true, load modules asynchronously even if
1121 * document ready has not yet occurred.
1122 */
1123 function request( dependencies, ready, error, async ) {
1124 var n;
1125
1126 // Allow calling by single module name
1127 if ( typeof dependencies === 'string' ) {
1128 dependencies = [dependencies];
1129 }
1130
1131 // Add ready and error callbacks if they were given
1132 if ( ready !== undefined || error !== undefined ) {
1133 jobs[jobs.length] = {
1134 'dependencies': filter(
1135 ['registered', 'loading', 'loaded'],
1136 dependencies
1137 ),
1138 'ready': ready,
1139 'error': error
1140 };
1141 }
1142
1143 // Queue up any dependencies that are registered
1144 dependencies = filter( ['registered'], dependencies );
1145 for ( n = 0; n < dependencies.length; n += 1 ) {
1146 if ( $.inArray( dependencies[n], queue ) === -1 ) {
1147 queue[queue.length] = dependencies[n];
1148 if ( async ) {
1149 // Mark this module as async in the registry
1150 registry[dependencies[n]].async = true;
1151 }
1152 }
1153 }
1154
1155 // Work the queue
1156 mw.loader.work();
1157 }
1158
1159 function sortQuery(o) {
1160 var sorted = {}, key, a = [];
1161 for ( key in o ) {
1162 if ( hasOwn.call( o, key ) ) {
1163 a.push( key );
1164 }
1165 }
1166 a.sort();
1167 for ( key = 0; key < a.length; key += 1 ) {
1168 sorted[a[key]] = o[a[key]];
1169 }
1170 return sorted;
1171 }
1172
1173 /**
1174 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1175 * to a query string of the form foo.bar,baz|bar.baz,quux
1176 * @private
1177 */
1178 function buildModulesString( moduleMap ) {
1179 var arr = [], p, prefix;
1180 for ( prefix in moduleMap ) {
1181 p = prefix === '' ? '' : prefix + '.';
1182 arr.push( p + moduleMap[prefix].join( ',' ) );
1183 }
1184 return arr.join( '|' );
1185 }
1186
1187 /**
1188 * Asynchronously append a script tag to the end of the body
1189 * that invokes load.php
1190 * @private
1191 * @param {Object} moduleMap Module map, see #buildModulesString
1192 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1193 * @param {string} sourceLoadScript URL of load.php
1194 * @param {boolean} async If true, use an asynchronous request even if document ready has not yet occurred
1195 */
1196 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
1197 var request = $.extend(
1198 { modules: buildModulesString( moduleMap ) },
1199 currReqBase
1200 );
1201 request = sortQuery( request );
1202 // Asynchronously append a script tag to the end of the body
1203 // Append &* to avoid triggering the IE6 extension check
1204 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
1205 }
1206
1207 /* Public Members */
1208 return {
1209 /**
1210 * The module registry is exposed as an aid for debugging and inspecting page
1211 * state; it is not a public interface for modifying the registry.
1212 *
1213 * @see #registry
1214 * @property
1215 * @private
1216 */
1217 moduleRegistry: registry,
1218
1219 /**
1220 * @inheritdoc #newStyleTag
1221 * @method
1222 */
1223 addStyleTag: newStyleTag,
1224
1225 /**
1226 * Batch-request queued dependencies from the server.
1227 */
1228 work: function () {
1229 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
1230 source, group, g, i, modules, maxVersion, sourceLoadScript,
1231 currReqBase, currReqBaseLength, moduleMap, l,
1232 lastDotIndex, prefix, suffix, bytesAdded, async;
1233
1234 // Build a list of request parameters common to all requests.
1235 reqBase = {
1236 skin: mw.config.get( 'skin' ),
1237 lang: mw.config.get( 'wgUserLanguage' ),
1238 debug: mw.config.get( 'debug' )
1239 };
1240 // Split module batch by source and by group.
1241 splits = {};
1242 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
1243
1244 // Appends a list of modules from the queue to the batch
1245 for ( q = 0; q < queue.length; q += 1 ) {
1246 // Only request modules which are registered
1247 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
1248 // Prevent duplicate entries
1249 if ( $.inArray( queue[q], batch ) === -1 ) {
1250 batch[batch.length] = queue[q];
1251 // Mark registered modules as loading
1252 registry[queue[q]].state = 'loading';
1253 }
1254 }
1255 }
1256
1257 mw.loader.store.init();
1258 if ( mw.loader.store.enabled ) {
1259 batch = $.grep( batch, function ( module ) {
1260 var source = mw.loader.store.get( module );
1261 if ( source ) {
1262 $.globalEval( source );
1263 return false; // Don't fetch
1264 }
1265 return true; // Fetch
1266 } );
1267 }
1268
1269 // Early exit if there's nothing to load...
1270 if ( !batch.length ) {
1271 return;
1272 }
1273
1274 // The queue has been processed into the batch, clear up the queue.
1275 queue = [];
1276
1277 // Always order modules alphabetically to help reduce cache
1278 // misses for otherwise identical content.
1279 batch.sort();
1280
1281 // Split batch by source and by group.
1282 for ( b = 0; b < batch.length; b += 1 ) {
1283 bSource = registry[batch[b]].source;
1284 bGroup = registry[batch[b]].group;
1285 if ( splits[bSource] === undefined ) {
1286 splits[bSource] = {};
1287 }
1288 if ( splits[bSource][bGroup] === undefined ) {
1289 splits[bSource][bGroup] = [];
1290 }
1291 bSourceGroup = splits[bSource][bGroup];
1292 bSourceGroup[bSourceGroup.length] = batch[b];
1293 }
1294
1295 // Clear the batch - this MUST happen before we append any
1296 // script elements to the body or it's possible that a script
1297 // will be locally cached, instantly load, and work the batch
1298 // again, all before we've cleared it causing each request to
1299 // include modules which are already loaded.
1300 batch = [];
1301
1302 for ( source in splits ) {
1303
1304 sourceLoadScript = sources[source].loadScript;
1305
1306 for ( group in splits[source] ) {
1307
1308 // Cache access to currently selected list of
1309 // modules for this group from this source.
1310 modules = splits[source][group];
1311
1312 // Calculate the highest timestamp
1313 maxVersion = 0;
1314 for ( g = 0; g < modules.length; g += 1 ) {
1315 if ( registry[modules[g]].version > maxVersion ) {
1316 maxVersion = registry[modules[g]].version;
1317 }
1318 }
1319
1320 currReqBase = $.extend( { version: formatVersionNumber( maxVersion ) }, reqBase );
1321 // For user modules append a user name to the request.
1322 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1323 currReqBase.user = mw.config.get( 'wgUserName' );
1324 }
1325 currReqBaseLength = $.param( currReqBase ).length;
1326 async = true;
1327 // We may need to split up the request to honor the query string length limit,
1328 // so build it piece by piece.
1329 l = currReqBaseLength + 9; // '&modules='.length == 9
1330
1331 moduleMap = {}; // { prefix: [ suffixes ] }
1332
1333 for ( i = 0; i < modules.length; i += 1 ) {
1334 // Determine how many bytes this module would add to the query string
1335 lastDotIndex = modules[i].lastIndexOf( '.' );
1336 // Note that these substr() calls work even if lastDotIndex == -1
1337 prefix = modules[i].substr( 0, lastDotIndex );
1338 suffix = modules[i].substr( lastDotIndex + 1 );
1339 bytesAdded = moduleMap[prefix] !== undefined
1340 ? suffix.length + 3 // '%2C'.length == 3
1341 : modules[i].length + 3; // '%7C'.length == 3
1342
1343 // If the request would become too long, create a new one,
1344 // but don't create empty requests
1345 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1346 // This request would become too long, create a new one
1347 // and fire off the old one
1348 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1349 moduleMap = {};
1350 async = true;
1351 l = currReqBaseLength + 9;
1352 }
1353 if ( moduleMap[prefix] === undefined ) {
1354 moduleMap[prefix] = [];
1355 }
1356 moduleMap[prefix].push( suffix );
1357 if ( !registry[modules[i]].async ) {
1358 // If this module is blocking, make the entire request blocking
1359 // This is slightly suboptimal, but in practice mixing of blocking
1360 // and async modules will only occur in debug mode.
1361 async = false;
1362 }
1363 l += bytesAdded;
1364 }
1365 // If there's anything left in moduleMap, request that too
1366 if ( !$.isEmptyObject( moduleMap ) ) {
1367 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1368 }
1369 }
1370 }
1371 },
1372
1373 /**
1374 * Register a source.
1375 *
1376 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1377 * @param {Object} props Object containing only the loadScript property which is a url to
1378 * the load.php location of the source.
1379 * @return {boolean}
1380 */
1381 addSource: function ( id, props ) {
1382 var source;
1383 // Allow multiple additions
1384 if ( typeof id === 'object' ) {
1385 for ( source in id ) {
1386 mw.loader.addSource( source, id[source] );
1387 }
1388 return true;
1389 }
1390
1391 if ( sources[id] !== undefined ) {
1392 throw new Error( 'source already registered: ' + id );
1393 }
1394
1395 sources[id] = props;
1396
1397 return true;
1398 },
1399
1400 /**
1401 * Register a module, letting the system know about it and its
1402 * properties. Startup modules contain calls to this function.
1403 *
1404 * @param {string} module Module name
1405 * @param {number} version Module version number as a timestamp (falls backs to 0)
1406 * @param {string|Array|Function} dependencies One string or array of strings of module
1407 * names on which this module depends, or a function that returns that array.
1408 * @param {string} [group=null] Group which the module is in
1409 * @param {string} [source='local'] Name of the source
1410 */
1411 register: function ( module, version, dependencies, group, source ) {
1412 var m;
1413 // Allow multiple registration
1414 if ( typeof module === 'object' ) {
1415 for ( m = 0; m < module.length; m += 1 ) {
1416 // module is an array of module names
1417 if ( typeof module[m] === 'string' ) {
1418 mw.loader.register( module[m] );
1419 // module is an array of arrays
1420 } else if ( typeof module[m] === 'object' ) {
1421 mw.loader.register.apply( mw.loader, module[m] );
1422 }
1423 }
1424 return;
1425 }
1426 // Validate input
1427 if ( typeof module !== 'string' ) {
1428 throw new Error( 'module must be a string, not a ' + typeof module );
1429 }
1430 if ( registry[module] !== undefined ) {
1431 throw new Error( 'module already registered: ' + module );
1432 }
1433 // List the module as registered
1434 registry[module] = {
1435 version: version !== undefined ? parseInt( version, 10 ) : 0,
1436 dependencies: [],
1437 group: typeof group === 'string' ? group : null,
1438 source: typeof source === 'string' ? source: 'local',
1439 state: 'registered'
1440 };
1441 if ( typeof dependencies === 'string' ) {
1442 // Allow dependencies to be given as a single module name
1443 registry[module].dependencies = [ dependencies ];
1444 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1445 // Allow dependencies to be given as an array of module names
1446 // or a function which returns an array
1447 registry[module].dependencies = dependencies;
1448 }
1449 },
1450
1451 /**
1452 * Implement a module given the components that make up the module.
1453 *
1454 * When #load or #using requests one or more modules, the server
1455 * response contain calls to this function.
1456 *
1457 * All arguments are required.
1458 *
1459 * @param {string} module Name of module
1460 * @param {Function|Array} script Function with module code or Array of URLs to
1461 * be used as the src attribute of a new `<script>` tag.
1462 * @param {Object} style Should follow one of the following patterns:
1463 * { "css": [css, ..] }
1464 * { "url": { <media>: [url, ..] } }
1465 * And for backwards compatibility (needs to be supported forever due to caching):
1466 * { <media>: css }
1467 * { <media>: [url, ..] }
1468 *
1469 * The reason css strings are not concatenated anymore is bug 31676. We now check
1470 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1471 *
1472 * @param {Object} msgs List of key/value pairs to be added to {@link mw#messages}.
1473 */
1474 implement: function ( module, script, style, msgs ) {
1475 // Validate input
1476 if ( typeof module !== 'string' ) {
1477 throw new Error( 'module must be a string, not a ' + typeof module );
1478 }
1479 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1480 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1481 }
1482 if ( !$.isPlainObject( style ) ) {
1483 throw new Error( 'style must be an object, not a ' + typeof style );
1484 }
1485 if ( !$.isPlainObject( msgs ) ) {
1486 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1487 }
1488 // Automatically register module
1489 if ( registry[module] === undefined ) {
1490 mw.loader.register( module );
1491 }
1492 // Check for duplicate implementation
1493 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1494 throw new Error( 'module already implemented: ' + module );
1495 }
1496 // Attach components
1497 registry[module].script = script;
1498 registry[module].style = style;
1499 registry[module].messages = msgs;
1500 // The module may already have been marked as erroneous
1501 if ( $.inArray( registry[module].state, ['error', 'missing'] ) === -1 ) {
1502 registry[module].state = 'loaded';
1503 if ( allReady( registry[module].dependencies ) ) {
1504 execute( module );
1505 }
1506 }
1507 },
1508
1509 /**
1510 * Execute a function as soon as one or more required modules are ready.
1511 *
1512 * @param {string|Array} dependencies Module name or array of modules names the callback
1513 * dependends on to be ready before executing
1514 * @param {Function} [ready] callback to execute when all dependencies are ready
1515 * @param {Function} [error] callback to execute when if dependencies have a errors
1516 */
1517 using: function ( dependencies, ready, error ) {
1518 var tod = typeof dependencies;
1519 // Validate input
1520 if ( tod !== 'object' && tod !== 'string' ) {
1521 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1522 }
1523 // Allow calling with a single dependency as a string
1524 if ( tod === 'string' ) {
1525 dependencies = [ dependencies ];
1526 }
1527 // Resolve entire dependency map
1528 dependencies = resolve( dependencies );
1529 if ( allReady( dependencies ) ) {
1530 // Run ready immediately
1531 if ( $.isFunction( ready ) ) {
1532 ready();
1533 }
1534 } else if ( filter( ['error', 'missing'], dependencies ).length ) {
1535 // Execute error immediately if any dependencies have errors
1536 if ( $.isFunction( error ) ) {
1537 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1538 dependencies );
1539 }
1540 } else {
1541 // Not all dependencies are ready: queue up a request
1542 request( dependencies, ready, error );
1543 }
1544 },
1545
1546 /**
1547 * Load an external script or one or more modules.
1548 *
1549 * @param {string|Array} modules Either the name of a module, array of modules,
1550 * or a URL of an external script or style
1551 * @param {string} [type='text/javascript'] mime-type to use if calling with a URL of an
1552 * external script or style; acceptable values are "text/css" and
1553 * "text/javascript"; if no type is provided, text/javascript is assumed.
1554 * @param {boolean} [async] If true, load modules asynchronously
1555 * even if document ready has not yet occurred. If false, block before
1556 * document ready and load async after. If not set, true will be
1557 * assumed if loading a URL, and false will be assumed otherwise.
1558 */
1559 load: function ( modules, type, async ) {
1560 var filtered, m, module, l;
1561
1562 // Validate input
1563 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1564 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1565 }
1566 // Allow calling with an external url or single dependency as a string
1567 if ( typeof modules === 'string' ) {
1568 // Support adding arbitrary external scripts
1569 if ( /^(https?:)?\/\//.test( modules ) ) {
1570 if ( async === undefined ) {
1571 // Assume async for bug 34542
1572 async = true;
1573 }
1574 if ( type === 'text/css' ) {
1575 // IE7-8 throws security warnings when inserting a <link> tag
1576 // with a protocol-relative URL set though attributes (instead of
1577 // properties) - when on HTTPS. See also bug #.
1578 l = document.createElement( 'link' );
1579 l.rel = 'stylesheet';
1580 l.href = modules;
1581 $( 'head' ).append( l );
1582 return;
1583 }
1584 if ( type === 'text/javascript' || type === undefined ) {
1585 addScript( modules, null, async );
1586 return;
1587 }
1588 // Unknown type
1589 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1590 }
1591 // Called with single module
1592 modules = [ modules ];
1593 }
1594
1595 // Filter out undefined modules, otherwise resolve() will throw
1596 // an exception for trying to load an undefined module.
1597 // Undefined modules are acceptable here in load(), because load() takes
1598 // an array of unrelated modules, whereas the modules passed to
1599 // using() are related and must all be loaded.
1600 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1601 module = registry[modules[m]];
1602 if ( module !== undefined ) {
1603 if ( $.inArray( module.state, ['error', 'missing'] ) === -1 ) {
1604 filtered[filtered.length] = modules[m];
1605 }
1606 }
1607 }
1608
1609 if ( filtered.length === 0 ) {
1610 return;
1611 }
1612 // Resolve entire dependency map
1613 filtered = resolve( filtered );
1614 // If all modules are ready, nothing to be done
1615 if ( allReady( filtered ) ) {
1616 return;
1617 }
1618 // If any modules have errors: also quit.
1619 if ( filter( ['error', 'missing'], filtered ).length ) {
1620 return;
1621 }
1622 // Since some modules are not yet ready, queue up a request.
1623 request( filtered, undefined, undefined, async );
1624 },
1625
1626 /**
1627 * Change the state of one or more modules.
1628 *
1629 * @param {string|Object} module module name or object of module name/state pairs
1630 * @param {string} state state name
1631 */
1632 state: function ( module, state ) {
1633 var m;
1634
1635 if ( typeof module === 'object' ) {
1636 for ( m in module ) {
1637 mw.loader.state( m, module[m] );
1638 }
1639 return;
1640 }
1641 if ( registry[module] === undefined ) {
1642 mw.loader.register( module );
1643 }
1644 if ( $.inArray( state, ['ready', 'error', 'missing'] ) !== -1
1645 && registry[module].state !== state ) {
1646 // Make sure pending modules depending on this one get executed if their
1647 // dependencies are now fulfilled!
1648 registry[module].state = state;
1649 handlePending( module );
1650 } else {
1651 registry[module].state = state;
1652 }
1653 },
1654
1655 /**
1656 * Get the version of a module.
1657 *
1658 * @param {string} module Name of module to get version for
1659 */
1660 getVersion: function ( module ) {
1661 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1662 return formatVersionNumber( registry[module].version );
1663 }
1664 return null;
1665 },
1666
1667 /**
1668 * @inheritdoc #getVersion
1669 * @deprecated since 1.18 use #getVersion instead
1670 */
1671 version: function () {
1672 return mw.loader.getVersion.apply( mw.loader, arguments );
1673 },
1674
1675 /**
1676 * Get the state of a module.
1677 *
1678 * @param {string} module name of module to get state for
1679 */
1680 getState: function ( module ) {
1681 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1682 return registry[module].state;
1683 }
1684 return null;
1685 },
1686
1687 /**
1688 * Get names of all registered modules.
1689 *
1690 * @return {Array}
1691 */
1692 getModuleNames: function () {
1693 return $.map( registry, function ( i, key ) {
1694 return key;
1695 } );
1696 },
1697
1698 /**
1699 * Load the `mediawiki.user` module.
1700 *
1701 * For backwards-compatibility with cached pages from before 2013 where:
1702 *
1703 * - the `mediawiki.user` module didn't exist yet
1704 * - `mw.user` was still part of mediawiki.js
1705 * - `mw.loader.go` still existed and called after `mw.loader.load()`
1706 */
1707 go: function () {
1708 mw.loader.load( 'mediawiki.user' );
1709 },
1710
1711 /**
1712 * @inheritdoc mw.inspect#runReports
1713 * @method
1714 */
1715 inspect: function () {
1716 var args = slice.call( arguments );
1717 mw.loader.using( 'mediawiki.inspect', function () {
1718 mw.inspect.runReports.apply( mw.inspect, args );
1719 } );
1720 },
1721
1722 /**
1723 * On browsers that implement the localStorage API, the module store serves as a
1724 * smart complement to the browser cache. Unlike the browser cache, the module store
1725 * can slice a concatenated response from ResourceLoader into its constituent
1726 * modules and cache each of them separately, using each module's versioning scheme
1727 * to determine when the cache should be invalidated.
1728 *
1729 * @singleton
1730 * @class mw.loader.store
1731 */
1732 store: {
1733 // Whether the store is in use on this page.
1734 enabled: null,
1735
1736 // The contents of the store, mapping '[module name]@[version]' keys
1737 // to module implementations.
1738 items: {},
1739
1740 // Cache hit stats
1741 stats: { hits: 0, misses: 0, expired: 0 },
1742
1743 /**
1744 * Construct a JSON-serializable object representing the content of the store.
1745 * @return {Object} Module store contents.
1746 */
1747 toJSON: function () {
1748 return { items: mw.loader.store.items, vary: mw.loader.store.getVary() };
1749 },
1750
1751 /**
1752 * Get the localStorage key for the entire module store. The key references
1753 * $wgDBname to prevent clashes between wikis which share a common host.
1754 *
1755 * @return {string} localStorage item key
1756 */
1757 getStoreKey: function () {
1758 return 'MediaWikiModuleStore:' + mw.config.get( 'wgDBname' );
1759 },
1760
1761 /**
1762 * Get a string key on which to vary the module cache.
1763 * @return {string} String of concatenated vary conditions.
1764 */
1765 getVary: function () {
1766 return [
1767 mw.config.get( 'skin' ),
1768 mw.config.get( 'wgResourceLoaderStorageVersion' ),
1769 mw.config.get( 'wgUserLanguage' )
1770 ].join(':');
1771 },
1772
1773 /**
1774 * Get a string key for a specific module. The key format is '[name]@[version]'.
1775 *
1776 * @param {string} module Module name
1777 * @return {string|null} Module key or null if module does not exist
1778 */
1779 getModuleKey: function ( module ) {
1780 return typeof registry[module] === 'object' ?
1781 ( module + '@' + registry[module].version ) : null;
1782 },
1783
1784 /**
1785 * Initialize the store by retrieving it from localStorage and (if successfully
1786 * retrieved) decoding the stored JSON value to a plain object.
1787 *
1788 * The try / catch block is used for JSON & localStorage feature detection.
1789 * See the in-line documentation for Modernizr's localStorage feature detection
1790 * code for a full account of why we need a try / catch: <http://git.io/4NEwKg>.
1791 */
1792 init: function () {
1793 var raw, data;
1794
1795 if ( mw.loader.store.enabled !== null ) {
1796 // #init already ran.
1797 return;
1798 }
1799
1800 if ( !mw.config.get( 'wgResourceLoaderStorageEnabled' ) || mw.config.get( 'debug' ) ) {
1801 // Disabled by configuration, or because debug mode is set.
1802 mw.loader.store.enabled = false;
1803 return;
1804 }
1805
1806 try {
1807 raw = localStorage.getItem( mw.loader.store.getStoreKey() );
1808 // If we get here, localStorage is available; mark enabled.
1809 mw.loader.store.enabled = true;
1810 data = JSON.parse( raw );
1811 if ( data && typeof data.items === 'object' && data.vary === mw.loader.store.getVary() ) {
1812 mw.loader.store.items = data.items;
1813 return;
1814 }
1815 } catch (e) {}
1816
1817 if ( raw === undefined ) {
1818 mw.loader.store.enabled = false; // localStorage failed; disable store.
1819 } else {
1820 mw.loader.store.update();
1821 }
1822 },
1823
1824 /**
1825 * Retrieve a module from the store and update cache hit stats.
1826 *
1827 * @param {string} module Module name
1828 * @return {string|boolean} Module implementation or false if unavailable
1829 */
1830 get: function ( module ) {
1831 var key;
1832
1833 if ( mw.loader.store.enabled !== true ) {
1834 return false;
1835 }
1836
1837 key = mw.loader.store.getModuleKey( module );
1838 if ( key in mw.loader.store.items ) {
1839 mw.loader.store.stats.hits++;
1840 return mw.loader.store.items[key];
1841 }
1842 mw.loader.store.stats.misses++;
1843 return false;
1844 },
1845
1846 /**
1847 * Stringify a module and queue it for storage.
1848 *
1849 * @param {string} module Module name
1850 * @param {Object} descriptor The module's descriptor as set in the registry
1851 */
1852 set: function ( module, descriptor ) {
1853 var args, key;
1854
1855 if ( mw.loader.store.enabled !== true ) {
1856 return false;
1857 }
1858
1859 key = mw.loader.store.getModuleKey( module );
1860
1861 if ( key in mw.loader.store.items ) {
1862 // Already set; decline to store.
1863 return false;
1864 }
1865
1866 if ( descriptor.state !== 'ready' ) {
1867 // Module failed to load; decline to store.
1868 return false;
1869 }
1870
1871 if ( !descriptor.version || $.inArray( descriptor.group, [ 'private', 'user', 'site' ] ) !== -1 ) {
1872 // Unversioned, private, or site-/user-specific; decline to store.
1873 return false;
1874 }
1875
1876 if ( $.inArray( undefined, [ descriptor.script, descriptor.style, descriptor.messages ] ) !== -1 ) {
1877 // Partial descriptor; decline to store.
1878 return false;
1879 }
1880
1881 try {
1882 args = [
1883 JSON.stringify( module ),
1884 typeof descriptor.script === 'function' ?
1885 String( descriptor.script ) : JSON.stringify( descriptor.script ),
1886 JSON.stringify( descriptor.style ),
1887 JSON.stringify( descriptor.messages )
1888 ];
1889 } catch (e) {
1890 return;
1891 }
1892 mw.loader.store.items[key] = 'mw.loader.implement(' + args.join(',') + ');';
1893 mw.loader.store.update();
1894 },
1895
1896 /**
1897 * Iterate through the module store, removing any item that does not correspond
1898 * (in name and version) to an item in the module registry.
1899 */
1900 prune: function () {
1901 var key, module;
1902
1903 if ( mw.loader.store.enabled !== true ) {
1904 return false;
1905 }
1906
1907 for ( key in mw.loader.store.items ) {
1908 module = key.substring( 0, key.indexOf( '@' ) );
1909 if ( mw.loader.store.getModuleKey( module ) !== key ) {
1910 mw.loader.store.stats.expired++;
1911 delete mw.loader.store.items[key];
1912 }
1913 }
1914 },
1915
1916 /**
1917 * Sync modules to localStorage.
1918 *
1919 * This function debounces localStorage updates. When called multiple times in
1920 * quick succession, the calls are coalesced into a single update operation.
1921 * This allows us to call #update without having to consider the module load
1922 * queue; the call to localStorage.setItem will be naturally deferred until the
1923 * page is quiescent.
1924 *
1925 * Because localStorage is shared by all pages with the same origin, if multiple
1926 * pages are loaded with different module sets, the possibility exists that
1927 * modules saved by one page will be clobbered by another. But the impact would
1928 * be minor and the problem would be corrected by subsequent page views.
1929 */
1930 update: ( function () {
1931 var timer;
1932
1933 function flush() {
1934 var data;
1935 if ( mw.loader.store.enabled !== true ) {
1936 return false;
1937 }
1938 mw.loader.store.prune();
1939 try {
1940 data = JSON.stringify( mw.loader.store );
1941 localStorage.setItem( mw.loader.store.getStoreKey(), data );
1942 } catch (e) {}
1943 }
1944
1945 return function () {
1946 clearTimeout( timer );
1947 timer = setTimeout( flush, 2000 );
1948 };
1949 }() )
1950 }
1951 };
1952 }() ),
1953
1954 /**
1955 * HTML construction helper functions
1956 *
1957 * @example
1958 *
1959 * var Html, output;
1960 *
1961 * Html = mw.html;
1962 * output = Html.element( 'div', {}, new Html.Raw(
1963 * Html.element( 'img', { src: '<' } )
1964 * ) );
1965 * mw.log( output ); // <div><img src="&lt;"/></div>
1966 *
1967 * @class mw.html
1968 * @singleton
1969 */
1970 html: ( function () {
1971 function escapeCallback( s ) {
1972 switch ( s ) {
1973 case '\'':
1974 return '&#039;';
1975 case '"':
1976 return '&quot;';
1977 case '<':
1978 return '&lt;';
1979 case '>':
1980 return '&gt;';
1981 case '&':
1982 return '&amp;';
1983 }
1984 }
1985
1986 return {
1987 /**
1988 * Escape a string for HTML. Converts special characters to HTML entities.
1989 * @param {string} s The string to escape
1990 */
1991 escape: function ( s ) {
1992 return s.replace( /['"<>&]/g, escapeCallback );
1993 },
1994
1995 /**
1996 * Create an HTML element string, with safe escaping.
1997 *
1998 * @param {string} name The tag name.
1999 * @param {Object} attrs An object with members mapping element names to values
2000 * @param {Mixed} contents The contents of the element. May be either:
2001 * - string: The string is escaped.
2002 * - null or undefined: The short closing form is used, e.g. <br/>.
2003 * - this.Raw: The value attribute is included without escaping.
2004 * - this.Cdata: The value attribute is included, and an exception is
2005 * thrown if it contains an illegal ETAGO delimiter.
2006 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
2007 */
2008 element: function ( name, attrs, contents ) {
2009 var v, attrName, s = '<' + name;
2010
2011 for ( attrName in attrs ) {
2012 v = attrs[attrName];
2013 // Convert name=true, to name=name
2014 if ( v === true ) {
2015 v = attrName;
2016 // Skip name=false
2017 } else if ( v === false ) {
2018 continue;
2019 }
2020 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
2021 }
2022 if ( contents === undefined || contents === null ) {
2023 // Self close tag
2024 s += '/>';
2025 return s;
2026 }
2027 // Regular open tag
2028 s += '>';
2029 switch ( typeof contents ) {
2030 case 'string':
2031 // Escaped
2032 s += this.escape( contents );
2033 break;
2034 case 'number':
2035 case 'boolean':
2036 // Convert to string
2037 s += String( contents );
2038 break;
2039 default:
2040 if ( contents instanceof this.Raw ) {
2041 // Raw HTML inclusion
2042 s += contents.value;
2043 } else if ( contents instanceof this.Cdata ) {
2044 // CDATA
2045 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
2046 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2047 }
2048 s += contents.value;
2049 } else {
2050 throw new Error( 'mw.html.element: Invalid type of contents' );
2051 }
2052 }
2053 s += '</' + name + '>';
2054 return s;
2055 },
2056
2057 /**
2058 * Wrapper object for raw HTML passed to mw.html.element().
2059 * @class mw.html.Raw
2060 */
2061 Raw: function ( value ) {
2062 this.value = value;
2063 },
2064
2065 /**
2066 * Wrapper object for CDATA element contents passed to mw.html.element()
2067 * @class mw.html.Cdata
2068 */
2069 Cdata: function ( value ) {
2070 this.value = value;
2071 }
2072 };
2073 }() ),
2074
2075 // Skeleton user object. mediawiki.user.js extends this
2076 user: {
2077 options: new Map(),
2078 tokens: new Map()
2079 },
2080
2081 /**
2082 * Registry and firing of events.
2083 *
2084 * MediaWiki has various interface components that are extended, enhanced
2085 * or manipulated in some other way by extensions, gadgets and even
2086 * in core itself.
2087 *
2088 * This framework helps streamlining the timing of when these other
2089 * code paths fire their plugins (instead of using document-ready,
2090 * which can and should be limited to firing only once).
2091 *
2092 * Features like navigating to other wiki pages, previewing an edit
2093 * and editing itself – without a refresh – can then retrigger these
2094 * hooks accordingly to ensure everything still works as expected.
2095 *
2096 * Example usage:
2097 *
2098 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2099 * mw.hook( 'wikipage.content' ).fire( $content );
2100 *
2101 * Handlers can be added and fired for arbitrary event names at any time. The same
2102 * event can be fired multiple times. The last run of an event is memorized
2103 * (similar to `$(document).ready` and `$.Deferred().done`).
2104 * This means if an event is fired, and a handler added afterwards, the added
2105 * function will be fired right away with the last given event data.
2106 *
2107 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2108 * Thus allowing flexible use and optimal maintainability and authority control.
2109 * You can pass around the `add` and/or `fire` method to another piece of code
2110 * without it having to know the event name (or `mw.hook` for that matter).
2111 *
2112 * var h = mw.hook( 'bar.ready' );
2113 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2114 *
2115 * Note: Events are documented with an underscore instead of a dot in the event
2116 * name due to jsduck not supporting dots in that position.
2117 *
2118 * @class mw.hook
2119 */
2120 hook: ( function () {
2121 var lists = {};
2122
2123 /**
2124 * Create an instance of mw.hook.
2125 *
2126 * @method hook
2127 * @member mw
2128 * @param {string} name Name of hook.
2129 * @return {mw.hook}
2130 */
2131 return function ( name ) {
2132 var list = lists[name] || ( lists[name] = $.Callbacks( 'memory' ) );
2133
2134 return {
2135 /**
2136 * Register a hook handler
2137 * @param {Function...} handler Function to bind.
2138 * @chainable
2139 */
2140 add: list.add,
2141
2142 /**
2143 * Unregister a hook handler
2144 * @param {Function...} handler Function to unbind.
2145 * @chainable
2146 */
2147 remove: list.remove,
2148
2149 /**
2150 * Run a hook.
2151 * @param {Mixed...} data
2152 * @chainable
2153 */
2154 fire: function () {
2155 return list.fireWith( null, slice.call( arguments ) );
2156 }
2157 };
2158 };
2159 }() )
2160 };
2161
2162 }( jQuery ) );
2163
2164 // Alias $j to jQuery for backwards compatibility
2165 window.$j = jQuery;
2166
2167 // Attach to window and globally alias
2168 window.mw = window.mediaWiki = mw;
2169
2170 // Auto-register from pre-loaded startup scripts
2171 if ( jQuery.isFunction( window.startUp ) ) {
2172 window.startUp();
2173 window.startUp = undefined;
2174 }